package com.bitdf.txing.group.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.bitdf.txing.common.enume.TxCodeEnume;
import com.bitdf.txing.common.utils.PageUtils;
import com.bitdf.txing.common.utils.R;
import com.bitdf.txing.group.ao.GroupCommentAo;
import com.bitdf.txing.group.entity.GroupCommentEntity;
import com.bitdf.txing.group.service.GroupCommentService;
import com.bitdf.txing.group.valid.SaveVaild;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author Lizhiwei
 * @email 123@qq.com
 * @date 2022-09-05 16:02:12
 */
@RestController
@RequestMapping("${txing.request.path.group}/comment")
public class GroupCommentController {
    @Autowired
    private GroupCommentService groupCommentService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = groupCommentService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        GroupCommentEntity groupComment = groupCommentService.getById(id);

        return R.ok().put("groupComment", groupComment);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @SaCheckLogin
    public R save(@RequestBody GroupCommentEntity groupComment) {
        groupCommentService.save(groupComment);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @SaCheckLogin
    public R update(@RequestBody GroupCommentEntity groupComment) {
        groupCommentService.updateById(groupComment);
        return R.ok();
    }

    /**
     * 删除评论
     */
    @GetMapping("/delete/{id}")
    @SaCheckLogin
    public R delete(@PathVariable("id") Integer id) {
        boolean b = groupCommentService.removeByIds1(id);
        return b ? R.ok() : R.error(TxCodeEnume.COMMON_SYSTEM_UNKNOWN_EXCEPTION);
    }

    /**
     * 评论组团
     *
     * @return
     */
    @PostMapping("/add")
    @SaCheckLogin
    public R modifyViewCount(@Validated(value = {SaveVaild.class}) @RequestBody GroupCommentAo groupCommentAo, BindingResult result) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return R.error(TxCodeEnume.COMMON_SUBMIT_DATA_EXCEPTION).put("data", errors);
        }
        Boolean b = groupCommentService.commentGroup(groupCommentAo.getGroupId(), groupCommentAo.getContent());
        return b ? R.ok() : R.error(TxCodeEnume.COMMON_SYSTEM_UNKNOWN_EXCEPTION);
    }


}
